package com.example.com.baruffini_mele.booking4u.authorization;

import java.math.BigInteger;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.HttpEntity;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.com.baruffini_mele.booking4u.R;



import android.content.res.Resources;

import android.util.Log;


/** The class JoomlaPasswordHandler manage credentials to allow
 * authertication on a Joomla server
*
* @author Carmen C. Baruffini
* @author G. Mele
* @version 1.0  Jan 5, 2013.
* 
*/

public class JoomlaPasswordHandler {
	private static final String TAG = "JoomlaPasswordHandler";	
	 
	private String userName; // 1st credential
	private String userPassword; //2nd credential
	private String userSalt; //salt estracted from saved hash
	private String savedHash; // remote hash saved in users database
	private String userHash; //re-generated hash
	

	 /**
		 * Default constructor for JoomlaPasswordHandler
		 * Sets properties: day userEmail and userPassword.
		 */
	public JoomlaPasswordHandler(String userName, String userPassword){
		super();
		this.userName = userName;
		this.userPassword = userPassword;
		//this.savedHash = hash;

	}
	
	
	/**
	 * Returns md5 hash of an input string
	 * 
	 * @param input String to encrypt in MD5
	 */
	private static String getMd5Hash(String input) {

        String md5 = null;
         
        if(null == input) return null;
         
        try {
             
        //Create MessageDigest object for MD5
        MessageDigest digest = MessageDigest.getInstance("MD5");
         
        //Update input string in message digest
        digest.update(input.getBytes(), 0, input.length());
 
        //Converts message digest value in base 16 (hex) 
        md5 = new BigInteger(1, digest.digest()).toString(16);
 
        } catch (NoSuchAlgorithmException e) {
 
            e.printStackTrace();
        }
        return md5;
    }
	
	
	/**
	 * 
	 * Create a HttpClient and a HttpPost objects to execute a POST request,
	 * use the properties userEmail and userPassword as POST parameters and asks
	 * to the remote authentication service the md5 hash associated to the
	 * corresponding user.Once obtained it, the hash is used to set
	 * the savedHash property.
	 *  
	 *
	 */
	
	
	public void postUserHashRequest() {
		String result = ""; //result obtained from remote query   
		String hash = "";
		//String urlString = Resources.getSystem().getString((R.string.URL_u_hash));
		String urlString = "http://143.225.162.99/~carmen/dieti/ws/u_hash.php";
//http post
		  		
		try{
		//Create  HttpClient and HttpPost objects to execute the POST request
		HttpClient httpclient = new DefaultHttpClient();
		
		HttpPost httppost = new HttpPost(urlString);
		//Set POST data
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("username",userName));
		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		//Execute the POST request
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity = response.getEntity();
		InputStream is = entity.getContent();
		
		
		
		//convert response to string
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
		     sb.append(line + "\n");
		}
		is.close();
		
		result=sb.toString();

		 } 
		catch(Exception e){
			e.printStackTrace();
		}

		//parse json data
		try{
		JSONArray jArray = new JSONArray(result);
		for(int i=0;i<jArray.length();i++){
		        JSONObject json_data = jArray.getJSONObject(i);
		        hash = json_data.getString("hash");
		        
		}
		
		}catch(JSONException e){
		Log.e(TAG, "Error parsing data "+e.toString());
		}
		savedHash = hash;
		
	}
	
	
	
	/**
	 * 
	 * Estract the salt splitting the remote hash
	 * on ":" and taking the second token.
	 * 
	 * @param hash
	 * @return salt
	 *  
	 */
	
	public String estractSalt(String hash){
		String salt = "";
		String tokens[]= hash.split(":");
		String estractedSalt = tokens[1];
		salt = estractedSalt;
		return salt;
		
	}
	
	/**
	 * 
	 * Return the MD5 Salted hash of a string
	 * 
	 * @param password to encrypt
	 * @return encriptedPassword 
	 *  
	 */
	public String encryptLocalPassword(String password) {
		String encriptedPassword = "";
		encriptedPassword = getMd5Hash(password.trim()+userSalt)+":"+userSalt;
		return encriptedPassword;
	}
	
	
	/**
	 * 
	 * Return true if user is correctly logged, false if not.
	 * 
	 * @return auth value 
	 *  
	 */
	public boolean accessAuthentication(){
		boolean auth = false;
		if(userHash.equals(savedHash)){
			auth = true;
			
		}
		return auth;
		
	}

	
		
	/**
	 * @return the user email
	 */
	
	public String getUserEmail() {
		return userName;
	}

	/**
	 *  set the property userEmail
	 */
	public void setUserEmail(String userEmail) {
		this.userName = userEmail;
	}

	/**
	 * @return the the user password
	 */
	public String getUserPassword() {
		return userPassword;
	}

	/**
	 *  set the property userPassword
	 */
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	/**
	 * @return the user salt 
	 */
	public String getUserSalt() {
		return userSalt;
	}

	
	/**
	 *  set the property userSalt
	 */
	public void setUserSalt(String salt) {
		this.userSalt = salt;
	}

	/**
	 * @return the re-generated local hash 
	 */
	public String getUserHash() {
		return userHash;
	}

	/**
	 *  set the property userHash with local hash obtained encripting the string obtained by
	 *  concatenating password and salt. After encrypting, result is
	 *  concatenated with salt again.
	 *  
	 */
	
	/*
	public void setUserHash() {
		this.userHash = getMd5Hash(userPassword.trim()+userSalt)+":"+userSalt;
	}

*/
	/**
	 * set the property userHash 
	 */
	public void setUserHash(String userhash) {
		this.userHash = userhash;
	}

	/**
	 * @return the remote hash
	 */
	public String getSavedHash() {
		return savedHash;
	}


 
	/**
	 * set saved hash with remote hash 
	 */
	public void setSavedHash(String savedHash) {
		this.savedHash = savedHash;
	}

}
